package com.fablesoft.projectdatacollect.ui;

import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;

import com.fablesoft.projectdatacollect.MyApplication;
import com.fablesoft.projectdatacollect.R;
import com.fablesoft.projectdatacollect.bean.BaseResponse;
import com.fablesoft.projectdatacollect.util.Config;
import com.fablesoft.projectdatacollect.util.EncryptionUtil;
import com.fablesoft.projectdatacollect.util.Log4jUtil;
import com.fablesoft.projectdatacollect.util.LogUtil;
import com.fablesoft.projectdatacollect.util.PatternUtils;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

@SuppressLint("HandlerLeak")
public class RegisterActivity extends BaseRequestActivity {

    private TextView RegisterBtn;
    private EditText passwordText;
    private EditText passwordagainText;
    private EditText userNameText;
    private EditText userindentityText;
    public static final int REGISTER_FINISH_CODE = 206;
    private ImageView eye;
    private LinearLayout setPasswordLayout;
    private LinearLayout getCodeLayout;
    private LinearLayout validateCodeLayout;
    private boolean mbDisplayFlg = false;
    
    String userindentity;
    String userName;
    String passNumber;
    String passAgainNumber;

    @Override protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        init();
    }

    private void init(){
        View titleBack = getTitleBack();
        titleBack.setVisibility(View.VISIBLE);
        titleBack.setOnClickListener(mClickListener);
        userindentityText =(EditText) findViewById(R.id.userindentity_text);
        userNameText =(EditText) findViewById(R.id.username_text);
        passwordagainText=(EditText) findViewById(R.id.password_again_text);
        passwordText =(EditText) findViewById(R.id.password_text);
        RegisterBtn = (TextView) findViewById(R.id.register_tv);
        //        eye =(ImageView) findViewById(R.id.eye);
        //        eye.setOnClickListener(mClickListener);
        RegisterBtn.setOnClickListener(mClickListener);
        
        userindentityText.addTextChangedListener(mTextWatcher);
        userNameText.addTextChangedListener(mTextWatcher);
        passwordagainText.addTextChangedListener(mTextWatcher);
        passwordText.addTextChangedListener(mTextWatcher);
    }

    TextWatcher mTextWatcher = new TextWatcher() {
		
		@Override
		public void onTextChanged(CharSequence s, int start, int before, int count) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void beforeTextChanged(CharSequence s, int start, int count,
				int after) {
			// TODO Auto-generated method stub
			
		}
		
		@Override
		public void afterTextChanged(Editable s) {
			// TODO Auto-generated method stub
			if(userindentityText.getText().length() > 0 && userNameText.getText().length() > 0
					 && passwordagainText.getText().length() > 0
					 && passwordText.getText().length() > 0){
				RegisterBtn.setEnabled(true);
				RegisterBtn.setBackgroundResource(R.drawable.button_round);
			}else{
				RegisterBtn.setEnabled(false);
				RegisterBtn.setBackgroundResource(R.drawable.round_disable_btn);
			}
		}
	};
    
    private OnClickListener mClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            switch (v.getId()) {
            case R.id.title_back:
                finish();
                break;
                //            case R.id.eye:
                //                if (!mbDisplayFlg) {
                //                    passwordText.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                //                    eye.setImageResource(R.drawable.eyea);
                //                } else {
                //                    passwordText.setTransformationMethod(PasswordTransformationMethod.getInstance());
                //                    eye.setImageResource(R.drawable.eye);
                //                }
                //                mbDisplayFlg = !mbDisplayFlg;
                //                passwordText.postInvalidate();
                //                break;
            case R.id.register_tv:
            	userindentity = userindentityText.getText().toString().trim();
                userName = userNameText.getText().toString().trim();
                passNumber = passwordText.getText().toString().trim();
                passAgainNumber = passwordagainText.getText().toString().trim();
                register(userindentity, userName, passNumber,passAgainNumber);
                break;
                //			case R.id.get_code_btn:
                //				action = "sendSmsVerifyCode.action";
                //				phone = phoneText.getEditableText().toString();
                //				new Thread(){
                //					public void run() {
                //						Map<String, Object> params = new HashMap<String, Object>();
                //						params.put("phone", phone);
                //						params.put("type", "1");
                //						String result = HttpUtil.post(action, params);
                //						Log.i("luzx", result);
                //					};
                //				}.start();
                //				break;
                //			case R.id.validate_code_btn:
                //				validateCodeLayout.setVisibility(View.INVISIBLE);
                //				setPasswordLayout.setVisibility(View.VISIBLE);
                //				break;
                //			case R.id.set_password_btn:
                //				finish();
                //				break;
                //			default:
                //				break;
            }
        }
    };

    private void register(String userindentity, String userName, String passNumber,String passAgainNumber){
    	if(TextUtils.isEmpty(userindentity)){
//            Toast.makeText(RegisterActivity.this, R.string.empty_idcard_hint, Toast.LENGTH_SHORT).show();
            return;
        }
        // 验证身份证号码
        try {
            if(PatternUtils.IDCardValidate(userindentity)==null){
//                Toast.makeText(
//                        getApplicationContext(),
//                        getResources().getString(
//                                R.string.user_register_page_illegal_idcard),
//                                Toast.LENGTH_SHORT).show();
                return ;
            }
        } catch (ParseException e) {
            Log4jUtil.e(e.toString());
            e.printStackTrace();
        }
        if(TextUtils.isEmpty(userName)){
            Toast.makeText(RegisterActivity.this, R.string.username_empty_hint, Toast.LENGTH_SHORT).show();
            return;
        }
        
        if(userName.length() < 4 || userName.length() > 12 || PatternUtils.isNumber(userName) || !PatternUtils.isNumberCharChinese(userName)){
//            Toast.makeText(RegisterActivity.this, R.string.illegal_username_hint, Toast.LENGTH_SHORT).show();
            return;
        }
        //验证密码
        if(TextUtils.isEmpty(passNumber)){
            Toast.makeText(RegisterActivity.this, R.string.password_hint, Toast.LENGTH_SHORT).show();
            return;
        }
        if(!PatternUtils.isLegalPassword(passNumber)){
//            Toast.makeText(RegisterActivity.this, R.string.notice_register_psw, Toast.LENGTH_SHORT).show();
            return;
        }
        if(!PatternUtils.isShuZiYing(passNumber)){
//            Toast.makeText(RegisterActivity.this, R.string.notice_register_psw, Toast.LENGTH_SHORT).show();
            return;
        }
        if(TextUtils.isEmpty(passAgainNumber)){
//            Toast.makeText(RegisterActivity.this, R.string.password_again_hint, Toast.LENGTH_SHORT).show();
            return;
        }
        if(!passNumber.equals(passAgainNumber)){
//            Toast.makeText(RegisterActivity.this, R.string.not_equal, Toast.LENGTH_SHORT).show();
            return;
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("loginName", userName);
        params.put("gmsfhm", userindentity);
        params.put("password", EncryptionUtil.md5Encrypt(passNumber));
        createLoadingDialog(RegisterActivity.this);
        MyApplication.getInstance().setSessionId("");
        showDialog("注册中");
        sendRequest(Config.LOGIN_URL, params, BaseResponse.class);
        RegisterBtn.setEnabled(false);
    }

    @Override
    public void onRequestFinish(BaseResponse response) {
        Message msg = mHandler.obtainMessage();
        msg.obj = response;
        mHandler.sendMessage(msg);
    };

    Handler mHandler = new Handler() {
        @Override
		public void handleMessage(Message msg) {
        	RegisterBtn.setEnabled(true);
            dismissDialog();
            BaseResponse result = (BaseResponse) msg.obj;
            if (result == null) {
                Toast.makeText(RegisterActivity.this, R.string.request_error,
                        Toast.LENGTH_SHORT).show();
            } else {
                LogUtil.v("Gao", result.toString());
                if("001000032".equals(result.getCode())){
//                	String content = getResources().getString(R.string.id_number) 
//                			+ userindentity 
//                			+ getResources().getString(R.string.registered_tip);
//                	createPromptDialog(RegisterActivity.this, null, content, 
//                			getResources().getString(R.string.straight_login), 
//                			getResources().getString(R.string.change_register), 
//                			new ConfirmClickListener() {
//								@Override
//								public void confirmClickImp() {
//									Intent i = new Intent();
//									i.putExtra("loginName", userindentity);
//									setResult(REGISTER_FINISH_CODE, i);
//									finish();
//								}
//							});
                }else{
                	Toast.makeText(RegisterActivity.this, result.getMessage(),
                            Toast.LENGTH_SHORT).show();
                }
                if(result.getSuccess()){
                	Intent i = new Intent();
					i.putExtra("loginName", userName);
					setResult(REGISTER_FINISH_CODE, i);
            	 	finish();
                }
            }
        };
    };
}
